import {useEffect, useState, createContext} from "react";
import {doGetHotTags, getLoginTypes, LoginType} from "../api/apis.ts";
import * as React from "react";
import {HotTag, TagInfo} from "../types/commonTypes.ts";

export const DataContext: React.Context<ShareData> = createContext({} as ShareData);
type ShareData = {
    loginTypes?: LoginType[],
    hotTags?: HotTag[],
    allTags?: TagInfo[]
} | null

export function DataProvider({children}: any) {
    const initShareData: ShareData = {
        loginTypes: [],
        hotTags: [],
    }
    const [data, setData] = useState(initShareData);
    useEffect(() => {
        const getLoginTypeInfo = async () => {
            const {code, data: resData} = await getLoginTypes();
            if (code === 200) {
                setData((prevState) => ({...prevState, loginTypes: resData}));
            }
        }
        const getHotTags = async () => {
            const {code, data: resData} = await doGetHotTags();
            if (code === 200) {
                setData((prevState) => ({
                    ...prevState,
                    hotTags: resData.topList,
                    allTags: resData.allList
                }));
            }
        }
        getLoginTypeInfo();
        getHotTags();
    }, []); // 注意这里的空数组，它表示只有在组件初次挂载时才会执行这个 effect

    return (
        <DataContext.Provider value={data}>
            {children}
        </DataContext.Provider>
    );
}